import oss2,os
from aliyunsdkcore.client import AcsClient
from aliyunsdkimm.request.v20170906.CreateOfficeConversionTaskRequest import CreateOfficeConversionTaskRequest
from aliyunsdkimm.request.v20170906.GetOfficeConversionTaskRequest import GetOfficeConversionTaskRequest
import json,time,configparser
import tools

config_file_path = tools.resource_path("ali/conf.ini")

class oss_util:
    AccessKeyId = ""
    AccessKeySecret = ""
    Region = ""
    BucketName = ""
    conf=configparser.ConfigParser()

    def __init__(self):
        self.conf.read(config_file_path, encoding="UTF-8")
        self.AccessKeyId = self.conf.get("authorization", "AccessKeyId")
        self.AccessKeySecret = self.conf.get("authorization", "AccessKeySecret")
        self.Region = self.conf.get("authorization", "Region")
        self.BucketName = self.conf.get("authorization", "BucketName")
        self.Domain = self.conf.get("authorization", "Domain")

        self.auth = oss2.Auth(self.AccessKeyId, self.AccessKeySecret)
        # Endpoint以杭州为例，其它Region请按实际情况填写。
        self.bucket = oss2.Bucket(self.auth, 'http://oss-cn-hangzhou.aliyuncs.com', self.BucketName)

    def upload(self,localpath,key):
        with open(localpath, 'rb') as fileobj:
            self.bucket.put_object(key, fileobj)
    def download(self,key,localpath):
        self.bucket.get_object_to_file(key, localpath)
    def get_url(self,key):
        return os.path.join(self.Domain,key)


class imm_util:
    AccessKeyId = ""
    AccessKeySecret = ""
    Region = ""

    conf=configparser.ConfigParser()

    def __init__(self):
        self.conf.read(config_file_path, encoding="UTF-8")
        self.AccessKeyId = self.conf.get("authorization", "AccessKeyId")
        self.AccessKeySecret = self.conf.get("authorization", "AccessKeySecret")
        self.Region = self.conf.get("authorization", "Region")
        self.BucketName = self.conf.get("authorization", "BucketName")

        self.client = AcsClient(self.AccessKeyId, self.AccessKeySecret, self.Region)


    def covert(self,key):
        createReq = CreateOfficeConversionTaskRequest()
        srcUri = "oss://" + tools.oss_path_join(self.BucketName,key)
        tgtUri = tools.key_to_dir(srcUri)
        # print(srcUri)
        # print(tgtUri)
        tgtType = "png"
        createReq.set_Project("uopx")
        createReq.set_SrcUri(srcUri)
        createReq.set_TgtUri(tgtUri)
        createReq.set_TgtType(tgtType)
        createReq.set_DisplayDpi(150) #96dpi 1280px, 300dpi 4000px,150dpi 2000px
        response = self.client.do_action_with_exception(createReq)

        res = json.loads(response)
        taskId = res["TaskId"]
        getReq = GetOfficeConversionTaskRequest()
        getReq.set_Project("uopx")
        getReq.set_TaskId(taskId)
        period = 3
        timeout = 600
        start = time.time()
        while True:
            time.sleep(period)
            response = json.loads(self.client.do_action_with_exception(getReq))
            # print(response)

            status = response["Status"]
            if status == "Finished":    #任务完成
                page_count = response['PageCount']
                return {"page_count": page_count,"message": ''}
            if status == "Failed":     #任务失败
                return {"page_count": -1, "message": response['FailDetail']['Code']}
            if time.time() - start > timeout:   #任务超时
                return {"page_count": -1, "message": '转换超时' + str(timeout) + "秒"}
